package com.bqnxzz.ywiigame;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.adjust.sdk.Adjust;
import com.adjust.sdk.AdjustAttribution;
import com.adjust.sdk.AdjustConfig;
import com.adjust.sdk.AdjustEvent;
import com.adjust.sdk.LogLevel;
import com.adjust.sdk.OnAttributionChangedListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.okgame.sdk.OkGame;
import com.okgame.sdk.advertiser.entity.AdParams;
import com.okgame.sdk.result.IResult;
import com.okgame.sdk.result.LoginInfo;
import com.okgame.sdk.result.NotifyInfo;
import com.okgame.sdk.result.OrderInfo;
import com.okgame.sdk.result.PaymentInfo;
import com.bqnxzz.ywiigame.nativeInterface.JSCall;
import com.bqnxzz.ywiigame.nativeInterface.XYNativeJSInterface;
import com.bqnxzz.ywiigame.util.HotUpdateUtil;
import com.bqnxzz.ywiigame.util.LocaleUtil;
import com.bqnxzz.ywiigame.util.ManifestUtil;
import com.bqnxzz.ywiigame.util.SoftHideKeyBoardUtil;
import com.bqnxzz.ywiigame.util.X5WebView;

public class MainActivity extends Activity {
    public final static String TAG = "H5_MainActivity";
    public final static int HTTP_PORT = 2888;

    public static String baseUrl = decrypt(BuildConfig.baseUrl);
    public static String gameGate = decrypt(BuildConfig.gameGate);

    private static final int SDK_VISITOR_LOGIN_FLAG = 1;
    private static final int SDK_FACEBOOK_LOGIN_FLAG = 2;
    private static final int SDK_GOOGLE_LOGIN_FLAG = 3;
    private static final int SDK_FACEBOOK_SHARE_FLAG = 4;
    private static final int SDK_GOOGLE_PAY_FLAG = 5;
    private static final int SDK_GET_INVITE_LINK_FLAG = 6;
    private static final int SDK_WHATSAPP_SHARE_FLAG = 7;
    private static final int SDK_NATIVE_SHARE_FLAG = 8;

    @SuppressLint("StaticFieldLeak")
    public static MainActivity self;

    public static ViewGroup rootLayer;
    public static PreloadingProxy preloadingProxy;
    public static X5WebView hallView;
    public static X5WebView gameView;

    private static XYNativeJSInterface jsInterface;
    public static int webViewStatus = 0;
    private static boolean activityCreated = false;
    public static boolean sdkInitFailed = true;
    private static String currSDKUserId = "";
    private static String advert = "1";
    private static String afStatus = "";
    private static String afCampaign = "";
    private static String afDetail = "";
    private static String afsdkName = "";
    private static String afreferId = "";
    private static String afarea = "";
    private static int getAttributionTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        OkGame.onCreate(MainActivity.this);
        hideBottomUIMenu();

        if (activityCreated) {
            Log.d(TAG, "reboot app");
            ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
            manager.restartPackage(BuildConfig.APPLICATION_ID + ".MainActivity");
            return;
        }

        Log.d(TAG, "start app");
        Log.i(TAG, "当前的Android版本是：" + Build.VERSION.SDK_INT);
        Log.i(TAG, "当前的系统语言是：" + LocaleUtil.getSystemLocale());

        MainActivity.self = this;
        setContentView(R.layout.main_activity);
        rootLayer = findViewById(R.id.rootLayer);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        jsInterface = new XYNativeJSInterface();

        initPreloading();
        initOrigin();
        initAdjust();

        HotUpdateUtil.checkJSPatch();
        SoftHideKeyBoardUtil.assistActivity(this);

        activityCreated = true;
    }

    @Override
    public void finish() {
        /**
         * 记住不要执行此句 super.finish(); 因为这是父类已经实现了该方法
         * 设置该activity永不过期，即不执行onDestroy()
         */
        moveTaskToBack(false);
    }

    public void initOrigin() {
        OkGame.init("origin", "123456",MainActivity.this, new IResult<String>() {
            @Override
            public void onSuccess(String s) {
                sdkInitFailed = false;
                Log.i(TAG, "初始化成功");
            }
            @Override
            public void onFail(String failMsg) {
                sdkInitFailed = true;
                Log.i(TAG, "初始化失败");
                showMsg(failMsg);
            }
        });
        OkGame.firebaseNotify(MainActivity.this, new IResult<NotifyInfo>() {
            @Override
            public void onSuccess(NotifyInfo notifyInfo) {
                NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
                Notification.Builder builder = new Notification.Builder(getApplicationContext());

                CharSequence notificationTitle = getString(R.string.app_name);
                long when = System.currentTimeMillis();

                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);

                final Random random = new Random(System.currentTimeMillis());
                int requestCode = random.nextInt();
                int notificationId = random.nextInt();
                PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(contentIntent)
                        .setSmallIcon(R.drawable.icon)
                        .setTicker(notificationTitle)
                        .setContentTitle(notificationTitle)
                        .setContentText(notifyInfo.getMessage())
                        .setWhen(when).setAutoCancel(true);
                Notification notification = builder.getNotification();
                notification.defaults = Notification.DEFAULT_ALL;
                notificationManager.notify(notificationId, notification);
            }
            @Override
            public void onFail(String s) {

            }
        });
    }

    public void getSystemLanguage() {
        String str = LocaleUtil.getSystemLocaleLanguage();
        Log.i(TAG, "当前的手机系统语言是：" + str);
        JSONObject json = new JSONObject();
        try {
            json.put("language", str);
            json.put("installSource", ManifestUtil.getInstallsource(MainActivity.this));
            json.put("advert", advert);
            json.put("afStatus", afStatus);
            json.put("afCampaign", afCampaign);
            json.put("afDetail", afDetail);
            json.put("versionCode", "" + ManifestUtil.getVersionCode(MainActivity.this));
        } catch (Exception e) {
        }
        callJsFunc("onGetSystemLanguageCallBack", json.toString());

        JSONObject json_1 = new JSONObject();
        try {
            json_1.put("sdkName", afsdkName);
            json_1.put("referId", afreferId);
            json_1.put("area", afarea);
            callJsFunc("onParentInviteInfo", json_1.toString());
        } catch (Exception e) {
        }
    }

    public void visitorLoginORIGIN() {
        Message msg = new Message();
        msg.what = SDK_VISITOR_LOGIN_FLAG;
        mHandler.sendMessage(msg);
    }

    public void facebookLoginORIGIN() {
        Message msg = new Message();
        msg.what = SDK_FACEBOOK_LOGIN_FLAG;
        mHandler.sendMessage(msg);
    }

    public void googleLoginORIGIN() {
        Message msg = new Message();
        msg.what = SDK_GOOGLE_LOGIN_FLAG;
        mHandler.sendMessage(msg);
    }

    public void facebookShareORIGIN(String jsonStr) {
        Message msg = new Message();
        msg.what = SDK_FACEBOOK_SHARE_FLAG;
        msg.obj = jsonStr;
        mHandler.sendMessage(msg);
    }

    public void whatsappShareORIGIN(String jsonStr) {
        Message msg = new Message();
        msg.what = SDK_WHATSAPP_SHARE_FLAG;
        msg.obj = jsonStr;
        mHandler.sendMessage(msg);
    }

    public void nativeShareORIGIN(String jsonStr) {
        Message msg = new Message();
        msg.what = SDK_NATIVE_SHARE_FLAG;
        msg.obj = jsonStr;
        mHandler.sendMessage(msg);
    }

    public void googlePayOrigin(String jsonStr) {
        Message msg = new Message();
        msg.what = SDK_GOOGLE_PAY_FLAG;
        msg.obj = jsonStr;
        mHandler.sendMessage(msg);
    }

    public void logoutOrigin() {
        OkGame.logout();
    }

    public void exitOrigin() {
        OkGame.exit(MainActivity.this, new IResult<String>() {
            @Override
            public void onSuccess(String s) {
            }
            @Override
            public void onFail(String failMsg) {
                Log.i(TAG, "Exit failed");
                showMsg(failMsg);
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_VISITOR_LOGIN_FLAG: {
                    if (sdkInitFailed){
                        showMsg("Not initialized, please reopen the game");
                        callJsFunc("onORIGINLoginFailedCallBack", "Login failed: Not initialized");
                        break;
                    }
                    OkGame.login(MainActivity.this, "1", new IResult<LoginInfo>() {
                        @Override
                        public void onSuccess(LoginInfo loginInfo) {
                            Log.i(TAG, "Login successed");
                            String uid = loginInfo.getUid(); //返回的账号的唯一标识
                            String token = loginInfo.getToken(); //登录验证token
                            currSDKUserId = loginInfo.getUid();
                            JSONObject json = new JSONObject();
                            try {
                                json.put("errCode", "0");
                                json.put("errMsg", "");
                                json.put("uid", uid);
                                json.put("token", token);
                                json.put("loginType", "1");
                                json.put("advert", advert);
                                json.put("afStatus", afStatus);
                                json.put("afCampaign", afCampaign);
                                json.put("afDetail", afDetail);
                                json.put("udid", OkGame.getDeviceId(MainActivity.self));
                                json.put("merchant", ManifestUtil.getChannel(MainActivity.this));
                                json.put("installSource", ManifestUtil.getInstallsource(MainActivity.this));
                            } catch (Exception e) {
                                json.put("errCode", "0");
                                json.put("errMsg", "");
                                json.put("uid", uid);
                                json.put("token", token);
                                json.put("loginType", "1");
                                json.put("advert", advert);
                                json.put("afStatus", afStatus);
                                json.put("afCampaign", afCampaign);
                                json.put("afDetail", "Exception");
                                json.put("udid", uid);
                                json.put("merchant", ManifestUtil.getChannel(MainActivity.this));
                                json.put("installSource", ManifestUtil.getInstallsource(MainActivity.this));
                            }
                            callJsFunc("onORIGINLoginCallBack", json.toString());
                        }
                        @Override
                        public void onFail(String failMsg) {
                            Log.i(TAG, "Login failed: " + failMsg);
                            callJsFunc("onORIGINLoginFailedCallBack", "Login failed: " + failMsg);
                        }
                    });
                    break;
                }
                case SDK_FACEBOOK_LOGIN_FLAG: {
                    if (sdkInitFailed){
                        showMsg("Not initialized, please reopen the game");
                        callJsFunc("onORIGINLoginFailedCallBack", "Login failed: Not initialized");
                        break;
                    }
                    OkGame.login(MainActivity.this, "2", new IResult<LoginInfo>() {
                        @Override
                        public void onSuccess(LoginInfo loginInfo) {
                            Log.i(TAG, "Login successed");
                            String uid = loginInfo.getUid(); //返回的账号的唯一标识
                            String token = loginInfo.getToken(); //登录验证token
                            currSDKUserId = loginInfo.getUid();
                            JSONObject json = new JSONObject();
                            try {
                                json.put("errCode", "0");
                                json.put("errMsg", "");
                                json.put("uid", uid);
                                json.put("token", token);
                                json.put("loginType", "2");
                                json.put("advert", advert);
                                json.put("afStatus", afStatus);
                                json.put("afCampaign", afCampaign);
                                json.put("afDetail", afDetail);
                                json.put("udid", OkGame.getDeviceId(MainActivity.self));
                                json.put("merchant", ManifestUtil.getChannel(MainActivity.this));
                                json.put("installSource", ManifestUtil.getInstallsource(MainActivity.this));
                            } catch (Exception e) {
                                json.put("errCode", "0");
                                json.put("errMsg", "");
                                json.put("uid", uid);
                                json.put("token", token);
                                json.put("loginType", "2");
                                json.put("advert", advert);
                                json.put("afStatus", afStatus);
                                json.put("afCampaign", afCampaign);
                                json.put("afDetail", "Exception");
                                json.put("udid", uid);
                                json.put("merchant", ManifestUtil.getChannel(MainActivity.this));
                                json.put("installSource", ManifestUtil.getInstallsource(MainActivity.this));
                            }
                            callJsFunc("onORIGINLoginCallBack", json.toString());
                        }
                        @Override
                        public void onFail(String failMsg) {
                            Log.i(TAG, "Login failed: " + failMsg);
                            callJsFunc("onORIGINLoginFailedCallBack", "Login failed: " + failMsg);
                        }
                    });
                    break;
                }
                case SDK_GOOGLE_LOGIN_FLAG: {
                    if (sdkInitFailed){
                        showMsg("Not initialized, please reopen the game");
                        callJsFunc("onORIGINLoginFailedCallBack", "Login failed: Not initialized");
                        break;
                    }
                    OkGame.login(MainActivity.this, "3", new IResult<LoginInfo>() {
                        @Override
                        public void onSuccess(LoginInfo loginInfo) {
                            Log.i(TAG, "Login successed");
                            String uid = loginInfo.getUid(); //返回的账号的唯一标识
                            String token = loginInfo.getToken(); //登录验证token
                            currSDKUserId = loginInfo.getUid();
                            JSONObject json = new JSONObject();
                            try {
                                json.put("errCode", "0");
                                json.put("errMsg", "");
                                json.put("uid", uid);
                                json.put("token", token);
                                json.put("loginType", "3");
                                json.put("advert", advert);
                                json.put("afStatus", afStatus);
                                json.put("afCampaign", afCampaign);
                                json.put("afDetail", afDetail);
                                json.put("udid", OkGame.getDeviceId(MainActivity.self));
                                json.put("merchant", ManifestUtil.getChannel(MainActivity.this));
                                json.put("installSource", ManifestUtil.getInstallsource(MainActivity.this));
                            } catch (Exception e) {
                                json.put("errCode", "0");
                                json.put("errMsg", "");
                                json.put("uid", uid);
                                json.put("token", token);
                                json.put("loginType", "3");
                                json.put("advert", advert);
                                json.put("afStatus", afStatus);
                                json.put("afCampaign", afCampaign);
                                json.put("afDetail", "Exception");
                                json.put("udid", uid);
                                json.put("merchant", ManifestUtil.getChannel(MainActivity.this));
                                json.put("installSource", ManifestUtil.getInstallsource(MainActivity.this));
                            }
                            callJsFunc("onORIGINLoginCallBack", json.toString());
                        }
                        @Override
                        public void onFail(String failMsg) {
                            Log.i(TAG, "Login failed: " + failMsg);
                            callJsFunc("onORIGINLoginFailedCallBack", "Login failed: " + failMsg);
                        }
                    });
                    break;
                }
                case SDK_FACEBOOK_SHARE_FLAG: {
                    String jsonStr = (String) msg.obj;
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        int type = jsonObject.getInteger("type");
                        String url = jsonObject.getString("url");
                        OkGame.facebookShare(MainActivity.this, type, url, new IResult<String>() {
                            @Override
                            public void onSuccess(String succMsg) {
                                JSONObject json = new JSONObject();
                                try {
                                    json.put("errCode", "0");
                                    json.put("errMsg", succMsg);
                                } catch (Exception e) {
                                }
                                Log.i(TAG, "Share successed");
                                callJsFunc("onORIGINFBShareCallBack", json.toString());
                            }
                            @Override
                            public void onFail(String failMsg) {
                                JSONObject json = new JSONObject();
                                try {
                                    json.put("errCode", "1");
                                    json.put("errMsg", failMsg);
                                } catch (Exception e) {
                                }
                                Log.i(TAG, "Share failed");
                                callJsFunc("onORIGINFBShareCallBack", json.toString());
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case SDK_WHATSAPP_SHARE_FLAG: {
                    String jsonStr = (String) msg.obj;
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        int type = jsonObject.getInteger("type");
                        String url = jsonObject.getString("url");
                        OkGame.whatsappShare(MainActivity.this, type, url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case SDK_NATIVE_SHARE_FLAG: {
                    String jsonStr = (String) msg.obj;
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        String url = jsonObject.getString("url");
                        OkGame.nativeShare(MainActivity.this, url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case SDK_GOOGLE_PAY_FLAG: {
                    String jsonStr = (String) msg.obj;
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        //SDK支付接口
                        PaymentInfo paymentInfo = new PaymentInfo();
                        paymentInfo.setUid(currSDKUserId);                                         //登录时成功拿到的UID  必须字段
                        paymentInfo.setServerId("1001");                                           //区服ID             必须字段
                        paymentInfo.setSubject(jsonObject.getString("subject"));            //商品名             必须字段
                        paymentInfo.setSubjectId(jsonObject.getString("subjectId"));        //商品ID              必须字段
                        paymentInfo.setRoleId(jsonObject.getString("roleId"));              //角色ID                必须字段
                        paymentInfo.setRoleLevel(jsonObject.getString("roleLevel"));        //角色等级            必须字段
                        paymentInfo.setRoleName(jsonObject.getString("roleName"));          //角色名             必须字段
                        paymentInfo.setCpBillNo(jsonObject.getString("cpBillNo"));          //CP订单号             必须字段
                        paymentInfo.setOrderAmount(jsonObject.getString("orderAmount"));    //订单金额,单位元       必须字段
                        paymentInfo.setExtraInfo(jsonObject.getString("extraInfo"));        //拓展信息        非必须字段
                        OkGame.pay(MainActivity.this, paymentInfo, new IResult<OrderInfo>() {
                            @Override
                            public void onSuccess(OrderInfo orderInfo) {
                                callJsFunc("onORIGINPayCallBack", orderInfo.toString());
                            }
                            @Override
                            public void onFail(String failMsg) {
                                callJsFunc("onORIGINPayFailedCallBack", failMsg);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case SDK_GET_INVITE_LINK_FLAG: {
                    String jsonStr = (String) msg.obj;
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        String s = BuildConfig.afLink + jsonObject.getString("referId");
                        callJsFunc("getInviteLinkCallBack", s);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    public void initAdjust() {
        AdjustConfig config = new AdjustConfig(MainActivity.this, BuildConfig.afKey, AdjustConfig.ENVIRONMENT_PRODUCTION);

        config.setLogLevel(LogLevel.WARN);

        config.setNeedsCost(true);

        config.setSendInBackground(true);

        getApplication().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) { }
            @Override
            public void onActivityStarted(@NonNull Activity activity) { }
            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                Adjust.onResume();
            }
            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                Adjust.onPause();
            }
            @Override
            public void onActivityStopped(@NonNull Activity activity) { }
            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) { }
            @Override
            public void onActivityDestroyed(@NonNull Activity activity) { }
        });

        config.setOnAttributionChangedListener(new OnAttributionChangedListener() {
            @Override
            public void onAttributionChanged(AdjustAttribution attribution) {
                Log.d(TAG, "Attribution: " + attribution.toString());

                try {
                    String referId = attribution.clickLabel;
                    Log.d(TAG, "The deep link will route to: " + referId);
                    afreferId = referId;
                    JSONObject json = new JSONObject();
                    json.put("sdkName", afsdkName);
                    json.put("referId", referId);
                    json.put("area", afarea);
                    callJsFunc("onParentInviteInfo", json.toString());
                } catch (Exception e) {
                    Log.d(TAG, "Custom param was not found in deep link data");
                }

                if (!Objects.isNull(attribution.campaign) && !attribution.campaign.equals("")) {
                    afCampaign = attribution.campaign;
                    if (Objects.isNull(afCampaign) || afCampaign.equals("")) {
                        afCampaign = "";
                    }
                    advert = "1";
                } else if (!Objects.isNull(attribution.fbInstallReferrer) && !attribution.fbInstallReferrer.equals("")) {
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(attribution.fbInstallReferrer);
                        afCampaign = jsonObject.getString("campaign_group_name");
                        if (Objects.isNull(afCampaign) || afCampaign.equals("")) {
                            afCampaign = jsonObject.getString("campaign_name");
                            if (Objects.isNull(afCampaign) || afCampaign.equals("")) {
                                afCampaign = "";
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        afCampaign = "";
                    }
                    advert = "1";
                } else {
                    afCampaign = "";
//                    advert = "0";
                }

                Log.d(TAG, "advert: " + advert);

                try {
                    if (!Objects.isNull(attribution.fbInstallReferrer) && !attribution.fbInstallReferrer.equals("")) {
                        JSONObject jsonObject = JSONObject.parseObject(attribution.fbInstallReferrer);
                        StringBuilder sb = new StringBuilder();
                        String trackerToken = "Facebook";
                        String campaignGroupId = jsonObject.getString("campaign_group_id");
                        if(campaignGroupId == null ) 	campaignGroupId = "";
                        String campaignGroupName = jsonObject.getString("campaign_group_name");
                        if(campaignGroupName == null ) 	campaignGroupName = "";
                        String campaignId = jsonObject.getString("campaign_id");
                        if(campaignId == null ) 	campaignId = "";
                        String campaignName = jsonObject.getString("campaign_name");
                        if(campaignName == null ) 	campaignName = "";
                        String adGroupId = jsonObject.getString("adgroup_id");
                        if(adGroupId == null ) 	adGroupId = "";
                        String adGroupName = jsonObject.getString("adgroup_name");
                        if(adGroupName == null ) 	adGroupName = "";
                        String creative = jsonObject.getString("ad_id");
                        if(creative == null ) 	creative = "";
                        String adid = attribution.adid;
                        if(adid == null ) 	adid = "";
                        sb.append("converData")
                                .append("#").append(trackerToken)
                                .append("#").append(campaignGroupId)
                                .append("#").append(campaignGroupName)
                                .append("#").append(campaignId)
                                .append("#").append(campaignName)
                                .append("#").append(adGroupId)
                                .append("#").append(adGroupName)
                                .append("#").append(creative)
                                .append("#").append(adid);
                        afDetail = sb.toString();
                    } else {
                        StringBuilder sb = new StringBuilder();
                        String trackerToken = attribution.trackerToken;
                        if(trackerToken == null ) 	trackerToken = "";
                        String trackerName = attribution.trackerName;
                        if(trackerName == null ) 	trackerName = "";
                        String network = attribution.network;
                        if(network == null ) 	network = "";
                        String campaign = attribution.campaign;
                        if(campaign == null ) 	campaign = "";
                        String adgroup = attribution.adgroup;
                        if(adgroup == null ) 	adgroup = "";
                        String creative = attribution.creative;
                        if(creative == null ) 	creative = "";
                        String adid = attribution.adid;
                        if(adid == null ) 	adid = "";
                        sb.append("converData")
                                .append("#").append(trackerToken)
                                .append("#").append(trackerName)
                                .append("#").append(network)
                                .append("#").append(campaign)
                                .append("#").append(adgroup)
                                .append("#").append(creative)
                                .append("#").append(adid);
                        afDetail = sb.toString();
                    }
                } catch (Exception e) {
                    Log.d(TAG, "Conversion param was not found in deep link data");
                    afDetail = e.toString();
                }
            }
        });

        Adjust.onCreate(config);
        Log.d(TAG, "Adjust version: " + Adjust.getSdkVersion());

        Adjust.sendFirstPackages();

        AdjustEvent adjustEvent = new AdjustEvent(BuildConfig.startToken);
        Adjust.trackEvent(adjustEvent);

        getAttribution();
    }

    public void getAttribution() {
        AdjustAttribution attribution = Adjust.getAttribution();
        if(attribution == null && getAttributionTime < 10) {
            getAttributionTime = getAttributionTime + 1;
            Log.d(TAG, "getAttribution null");
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    getAttribution();
                }
            }, 1000);// 这里是毫秒
        } else {
            if(attribution == null){
                Log.d(TAG, "getAttribution null");
                afDetail = Adjust.getAdid();
                if (Objects.isNull(afDetail) || afDetail.equals("")) {
                    afDetail = "failed";
                }
                MainActivity.self.runOnUiThread(() -> MainActivity.self.startNative());
                return;
            }

            Log.d(TAG, "Attribution: " + attribution.toString());

            try {
                String referId = attribution.clickLabel;
                Log.d(TAG, "The deep link will route to: " + referId);
                afreferId = referId;
                JSONObject json = new JSONObject();
                json.put("sdkName", afsdkName);
                json.put("referId", referId);
                json.put("area", afarea);
                callJsFunc("onParentInviteInfo", json.toString());
            } catch (Exception e) {
                Log.d(TAG, "Custom param was not found in deep link data");
            }

            if (!Objects.isNull(attribution.campaign) && !attribution.campaign.equals("")) {
                afCampaign = attribution.campaign;
                if (Objects.isNull(afCampaign) || afCampaign.equals("")) {
                    afCampaign = "";
                }
                advert = "1";
            } else if (!Objects.isNull(attribution.fbInstallReferrer) && !attribution.fbInstallReferrer.equals("")) {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(attribution.fbInstallReferrer);
                    afCampaign = jsonObject.getString("campaign_group_name");
                    if (Objects.isNull(afCampaign) || afCampaign.equals("")) {
                        afCampaign = jsonObject.getString("campaign_name");
                        if (Objects.isNull(afCampaign) || afCampaign.equals("")) {
                            afCampaign = "";
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    afCampaign = "";
                }
                advert = "1";
            } else {
                afCampaign = "";
//                advert = "0";
            }

            Log.d(TAG, "advert: " + advert);

            try {
                if (!Objects.isNull(attribution.fbInstallReferrer) && !attribution.fbInstallReferrer.equals("")) {
                    JSONObject jsonObject = JSONObject.parseObject(attribution.fbInstallReferrer);
                    StringBuilder sb = new StringBuilder();
                    String trackerToken = "Facebook";
                    String campaignGroupId = jsonObject.getString("campaign_group_id");
                    if(campaignGroupId == null ) 	campaignGroupId = "";
                    String campaignGroupName = jsonObject.getString("campaign_group_name");
                    if(campaignGroupName == null ) 	campaignGroupName = "";
                    String campaignId = jsonObject.getString("campaign_id");
                    if(campaignId == null ) 	campaignId = "";
                    String campaignName = jsonObject.getString("campaign_name");
                    if(campaignName == null ) 	campaignName = "";
                    String adGroupId = jsonObject.getString("adgroup_id");
                    if(adGroupId == null ) 	adGroupId = "";
                    String adGroupName = jsonObject.getString("adgroup_name");
                    if(adGroupName == null ) 	adGroupName = "";
                    String creative = jsonObject.getString("ad_id");
                    if(creative == null ) 	creative = "";
                    String adid = attribution.adid;
                    if(adid == null ) 	adid = "";
                    sb.append("converData")
                            .append("#").append(trackerToken)
                            .append("#").append(campaignGroupId)
                            .append("#").append(campaignGroupName)
                            .append("#").append(campaignId)
                            .append("#").append(campaignName)
                            .append("#").append(adGroupId)
                            .append("#").append(adGroupName)
                            .append("#").append(creative)
                            .append("#").append(adid);
                    afDetail = sb.toString();
                } else {
                    StringBuilder sb = new StringBuilder();
                    String trackerToken = attribution.trackerToken;
                    if(trackerToken == null ) 	trackerToken = "";
                    String trackerName = attribution.trackerName;
                    if(trackerName == null ) 	trackerName = "";
                    String network = attribution.network;
                    if(network == null ) 	network = "";
                    String campaign = attribution.campaign;
                    if(campaign == null ) 	campaign = "";
                    String adgroup = attribution.adgroup;
                    if(adgroup == null ) 	adgroup = "";
                    String creative = attribution.creative;
                    if(creative == null ) 	creative = "";
                    String adid = attribution.adid;
                    if(adid == null ) 	adid = "";
                    sb.append("converData")
                            .append("#").append(trackerToken)
                            .append("#").append(trackerName)
                            .append("#").append(network)
                            .append("#").append(campaign)
                            .append("#").append(adgroup)
                            .append("#").append(creative)
                            .append("#").append(adid);
                    afDetail = sb.toString();
                }
            } catch (Exception e) {
                Log.d(TAG, "Conversion param was not found in deep link data");
                afDetail = e.toString();
            }

            MainActivity.self.runOnUiThread(() -> MainActivity.self.startNative());
        }
    }

    public void getInviteLink(String jsonStr){
        Message msg = new Message();
        msg.what = SDK_GET_INVITE_LINK_FLAG;
        msg.obj = jsonStr;
        mHandler.sendMessage(msg);
    }

    //登录
    public void trackEventLogin(String jsonStr) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            String userID = jsonObject.getString("userID");
            String eLoginType = jsonObject.getString("eLoginType");
            Log.d(TAG, "trackEventLogin: " + userID + ", eLoginType: " + eLoginType);

            AdjustEvent adjustEvent = new AdjustEvent(BuildConfig.loginToken);
            adjustEvent.addCallbackParameter("userID", userID);
            adjustEvent.addCallbackParameter("eLoginType", eLoginType);
            Adjust.trackEvent(adjustEvent);

            AdParams params = new AdParams();
            params.eventName = "login";
            Map<String, String> eventParams = new HashMap<String, String>();
            eventParams.put("method", eLoginType); //登录类型
            params.params = eventParams;
            OkGame.trackEvent(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //注册
    public void trackEventRegister(String jsonStr) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            String userID = jsonObject.getString("userID");
            String eRegisterType = jsonObject.getString("eRegisterType");
            Log.d(TAG, "trackEventRegister: " + userID + ", eRegisterType: " + eRegisterType);

            AdjustEvent adjustEvent = new AdjustEvent(BuildConfig.registrationToken);
            adjustEvent.addCallbackParameter("userID", userID);
            adjustEvent.addCallbackParameter("registrationMethod", eRegisterType);
            Adjust.trackEvent(adjustEvent);

            AdParams params = new AdParams();
            params.registrationMethod = eRegisterType;
            OkGame.trackRegister(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //购买
    public void trackEventBuy(String jsonStr) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            String userID = jsonObject.getString("userID");
            String currency = jsonObject.getString("currency");
            String revenue = jsonObject.getString("revenue");
            String goodID = jsonObject.getString("goodID");
            String orderID = jsonObject.getString("orderID");
            String receiptID = jsonObject.getString("receiptID");
            String payType = jsonObject.getString("payType");
            String goodName = jsonObject.getString("goodName");
            String goodNum = jsonObject.getString("goodNum");
            Log.d(TAG, "trackEventBuy: "+userID+",revenue:"+revenue+",goodNum:"+goodNum+",currency:"+currency+",goodID:"+goodID+",orderID:"+orderID+",receiptID:"+receiptID+",payType:"+payType+",goodName:"+goodName);

            AdjustEvent adjustEvent = new AdjustEvent(BuildConfig.purchaseToken);
            adjustEvent.setRevenue(Double.parseDouble(revenue), currency);
            adjustEvent.setOrderId(orderID);
            adjustEvent.addCallbackParameter("userID", userID);
            adjustEvent.addCallbackParameter("payRevenue", revenue);
            adjustEvent.addCallbackParameter("payCurrency", currency);
            adjustEvent.addCallbackParameter("orderId", orderID);
            Adjust.trackEvent(adjustEvent);

            AdParams params = new AdParams();
            params.payRevenue = Double.parseDouble(revenue);
            params.payCurrency = currency;
            params.orderId = orderID;
            OkGame.trackPurchase(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //自定义事件
    public void trackEvent(String jsonStr) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            String userID = jsonObject.getString("userID");
            String mainKey = jsonObject.getString("mainKey");
            String eventKey = jsonObject.getString("eventKey");
            String eventContent = jsonObject.getString("eventContent");
            Log.d(TAG, "trackEvent: " + userID + ", mainKey: " + mainKey);

            AdjustEvent adjustEvent = new AdjustEvent(eventKey);
            Adjust.trackEvent(adjustEvent);

            AdParams params = new AdParams();
            params.eventName = mainKey;
            Map<String, String> eventParams = new HashMap<String, String>();
            eventParams.put("userID", userID); //玩家ID
            eventParams.put(eventKey, eventContent); //事件内容
            params.params = eventParams;
            OkGame.trackEvent(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initPreloading() {
        preloadingProxy = new PreloadingProxy(
                findViewById(R.id.preloadingLayer),
                findViewById(R.id.progressBar),
                findViewById(R.id.textView),
                findViewById(R.id.versionTf)
        );
        preloadingProxy.startInit();
    }

    public void closePreloading() {
        rootLayer.removeView(preloadingProxy.rootLayer);
        preloadingProxy.dispose();
    }

    @Override
    protected void onStart() {
        super.onStart();
        OkGame.onStart(MainActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        hideBottomUIMenu();
        OkGame.onResume(MainActivity.this);

        if (webViewStatus == 1) {
            if (hallView != null) {
                hallView.onResume();
                hallView.loadUrl("javascript:if(egret){egret.lifecycle.onResume();}");
            }
        } else if (webViewStatus == 2) {
            if (gameView != null) {
                gameView.onResume();
                gameView.loadUrl("javascript:if(egret){egret.lifecycle.onResume();}");
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        OkGame.onPause(MainActivity.this);

        if (webViewStatus == 1) {
            if (hallView != null) {
                hallView.onPause();
                hallView.loadUrl("javascript:if(egret){egret.lifecycle.onPause();}");
            }
        } else if (webViewStatus == 2) {
            if (gameView != null) {
                gameView.onPause();
                gameView.loadUrl("javascript:if(egret){egret.lifecycle.onPause();}");
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        OkGame.onStop(MainActivity.this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        OkGame.onRestart(MainActivity.this);
    }

    @Override
    protected void onDestroy() {
        OkGame.onDestroy(MainActivity.this);
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        OkGame.onActivityResult(MainActivity.this, requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == X5WebView.CHOOSER_REQUEST) {
            if (webViewStatus == 1) {
                hallView.onActivityResultFileChooser(requestCode, resultCode, data);
            } else if (webViewStatus == 2){
                gameView.onActivityResultFileChooser(requestCode, resultCode, data);
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        OkGame.onNewIntent(MainActivity.this, intent);
        super.onNewIntent(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        OkGame.onRequestPermissionsResult(requestCode,permissions,grantResults);
        if (requestCode == X5WebView.PERMISSION_REQUEST) {
            if (grantResults.length > 0){
                for (int result : grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(getApplicationContext(), "You need permission to use this function", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT <19) {
            //lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptiOns= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility( uiOptiOns);
        }
    }

    public void startNative() {
        initHallView();
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    public void initHallView() {
        if (hallView != null) {
            return;
        }
        hallView = new X5WebView(this);
        hallView.addJavascriptInterface(jsInterface, "xyNative");
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        hallView.setLayoutParams(lp);
        
        rootLayer.addView(hallView, 0);

        String gameUrl = baseUrl + "/hall/index.html?v=" + System.currentTimeMillis() + "&ip=" + gameGate + "&ssl=1";

//        Log.d(TAG, "加载大厅:" + gameUrl);
        hallView.loadUrl(gameUrl);
        
        webViewStatus = 1;
    }

    public void startLoadGame(String basicConfig) {
        if (this.gameView == null) {
            gameView = new X5WebView(this);
            gameView.addJavascriptInterface(jsInterface, "xyNative");
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
            gameView.setLayoutParams(lp);
        }
        gameView.initJsData = basicConfig;
        JSONObject json = JSON.parseObject(basicConfig);
        String gameId = json.getString("gameId").toLowerCase();

        String gameUrl = baseUrl + "/" + gameId + "/index.html?v=" + System.currentTimeMillis() + "&ip=" + gameGate + "&ssl=1";
        
        Log.d(TAG, basicConfig);

        rootLayer.addView(gameView, 0);
        gameView.loadUrl(gameUrl);
    }

    public void showGame() {
        rootLayer.removeView(hallView);
        gameView.onResume();
        gameView.setScrollY(0);
        webViewStatus = 2;
    }

    public void unloadGame() {
        hallView.setScrollY(0);
        if (hallView.getParent() == rootLayer) {
            rootLayer.removeView(hallView);
        }
        rootLayer.addView(hallView);

        hallView.onResume();

        if (gameView != null) {
            if (gameView.getParent() == rootLayer) {
                rootLayer.removeView(gameView);
            }
            gameView.loadUrl("about:blank");
        }

        webViewStatus = 1;
    }

    public void setLayoutWithNoKeyboard() {
        if (gameView != null) {
            gameView.setScrollY(0);
            gameView.setTop(0);
            gameView.callJS(JSCall.layoutWithNoKeyboard);
        }
        if (hallView != null) {
            hallView.setScrollY(0);
            hallView.setTop(0);
            hallView.callJS(JSCall.layoutWithNoKeyboard);
        }
    }

    public void setLayoutWithKeyboard(int offsetY) {
        if (gameView != null) {
            gameView.setScrollY(offsetY);
            gameView.setTop(-offsetY);
        }
        if (hallView != null) {
            hallView.setScrollY(offsetY);
            hallView.setTop(-offsetY);
        }
    }

    public void readyToLayoutWithKeyboard(int offset, int maxHeight) {
        JSONObject param = new JSONObject();
        param.put("offsetY", offset);
        param.put("maxHeight", maxHeight);
        if (webViewStatus == 1) {
            hallView.callJS(JSCall.layoutWithKeyboard, param.toJSONString());
        } else if (webViewStatus == 2) {
            gameView.callJS(JSCall.layoutWithKeyboard, param.toJSONString());
        }
    }

    public void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    public void callJsFunc(String funcName, String param) {
        Log.i(TAG, "################## 回调JS接口 START ################");
        Log.i(TAG, "WebView status: " + webViewStatus);
        Log.i(TAG, "Callback function: " + funcName);
        Log.i(TAG, "Param: " + param);
        Log.i(TAG, "################## 回调JS接口 END ##################");
        if (webViewStatus == 1) {
            hallView.callJS(funcName, param);
        } else if (webViewStatus == 2) {
            gameView.callJS(funcName, param);
        } else {
            Log.i(TAG, "JS对象为空");
        }
    }

    public static String encrypt(String input) {
        byte[] encodedBytes = Base64.getEncoder().encode(input.getBytes());
        return new String(encodedBytes);
    }

    public static String decrypt(String input) {
        byte[] decodedBytes = Base64.getDecoder().decode(input);
        return new String(decodedBytes);
    }
}
